package com.dove.aliyunzhibosdkdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceView;

import com.alivc.component.custom.AlivcLivePushCustomDetect;
import com.alivc.component.custom.AlivcLivePushCustomFilter;
import com.alivc.live.detect.TaoFaceFilter;
import com.alivc.live.filter.TaoBeautyFilter;
import com.alivc.live.pusher.AlivcAudioAACProfileEnum;
import com.alivc.live.pusher.AlivcFpsEnum;
import com.alivc.live.pusher.AlivcLivePushBGMListener;
import com.alivc.live.pusher.AlivcLivePushConfig;
import com.alivc.live.pusher.AlivcLivePushError;
import com.alivc.live.pusher.AlivcLivePushErrorListener;
import com.alivc.live.pusher.AlivcLivePushInfoListener;
import com.alivc.live.pusher.AlivcLivePushNetworkListener;
import com.alivc.live.pusher.AlivcLivePusher;
import com.alivc.live.pusher.AlivcPreviewDisplayMode;
import com.alivc.live.pusher.AlivcPreviewOrientationEnum;
import com.alivc.live.pusher.AlivcQualityModeEnum;
import com.alivc.live.pusher.AlivcResolutionEnum;

public class MyLivePushActivity extends AppCompatActivity {

    private static final String URL_KEY = "url_key";
    private static final String ASYNC_KEY = "async_key";
    private static final String AUDIO_ONLY_KEY = "audio_only_key";
    private static final String VIDEO_ONLY_KEY = "video_only_key";
    private static final String ORIENTATION_KEY = "orientation_key";
    private static final String CAMERA_ID = "camera_id";
    private static final String FLASH_ON = "flash_on";
    private static final String AUTH_TIME = "auth_time";
    private static final String PRIVACY_KEY = "privacy_key";
    private static final String MIX_EXTERN = "mix_extern";
    private static final String MIX_MAIN = "mix_main";
    public static final int REQ_CODE_PUSH = 0x1112;

    private AlivcLivePusher mAlivcLivePusher = null;
    TaoFaceFilter taoFaceFilter;
    TaoBeautyFilter taoBeautyFilter;
    private AlivcLivePushConfig mAlivcLivePushConfig;
    public SurfaceView mPreviewView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mypushlive);

        initId();

        mAlivcLivePusher = new AlivcLivePusher();
        initSet();
        initPusher();
        mAlivcLivePusher.startPreview(mPreviewView);//开始预览，也可根据需求调用异步接口startPreviewAysnc来实现
//        mAlivcLivePusher.startPush(mPushUrl);
    }

    /**
     * 初始化控件id
     */
    private void initId() {
        mPreviewView = findViewById(R.id.preview_view);
    }

    /**
     * 初始化推流器
     */
    private void initPusher() {
        mAlivcLivePushConfig = (AlivcLivePushConfig) getIntent().getSerializableExtra(AlivcLivePushConfig.CONFIG);
        AlivcLivePusher mAlivcLivePusher = new AlivcLivePusher();
        mAlivcLivePusher.init(this, mAlivcLivePushConfig);

        /**
         * 设置推流错误事件
         *
         * @param errorListener 错误监听器
         */
        mAlivcLivePusher.setLivePushErrorListener(new AlivcLivePushErrorListener() {
            @Override
            public void onSystemError(AlivcLivePusher livePusher, AlivcLivePushError error) {
                if(error != null) {
                    //添加UI提示或者用户自定义的错误处理
                }
            }
            @Override
            public void onSDKError(AlivcLivePusher livePusher, AlivcLivePushError error) {
                if(error != null) {
                    //添加UI提示或者用户自定义的错误处理
                }
            }
        });
        /**
         * 设置推流通知事件
         *
         * @param infoListener 通知监听器
         */
        mAlivcLivePusher.setLivePushInfoListener(new AlivcLivePushInfoListener() {
            @Override
            public void onPreviewStarted(AlivcLivePusher pusher) {
                //预览开始通知
            }
            @Override
            public void onPreviewStoped(AlivcLivePusher pusher) {
                //预览结束通知
            }
            @Override
            public void onPushStarted(AlivcLivePusher pusher) {
                //推流开始通知
            }

            @Override
            public void onFirstAVFramePushed(AlivcLivePusher alivcLivePusher) {

            }

            @Override
            public void onPushPauesed(AlivcLivePusher pusher) {
                //推流暂停通知
            }
            @Override
            public void onPushResumed(AlivcLivePusher pusher) {
                //推流恢复通知
            }
            @Override
            public void onPushStoped(AlivcLivePusher pusher) {
                //推流停止通知
            }
            @Override
            public void onPushRestarted(AlivcLivePusher pusher) {
                //推流重启通知
            }
            @Override
            public void onFirstFramePreviewed(AlivcLivePusher pusher) {
                //首帧渲染通知
            }
            @Override
            public void onDropFrame(AlivcLivePusher pusher, int countBef, int countAft) {
                //丢帧通知
            }
            @Override
            public void onAdjustBitRate(AlivcLivePusher pusher, int curBr, int targetBr) {
                //调整码率通知
            }
            @Override
            public void onAdjustFps(AlivcLivePusher pusher, int curFps, int targetFps) {
                //调整帧率通知
            }
        });
        /**
         * 设置网络通知事件
         *
         * @param infoListener 通知监听器
         */
        mAlivcLivePusher.setLivePushNetworkListener(new AlivcLivePushNetworkListener() {
            @Override
            public void onNetworkPoor(AlivcLivePusher pusher) {
                //网络差通知
            }
            @Override
            public void onNetworkRecovery(AlivcLivePusher pusher) {
                //网络恢复通知
            }
            @Override
            public void onReconnectStart(AlivcLivePusher pusher) {
                //重连开始通知
            }
            @Override
            public void onReconnectFail(AlivcLivePusher pusher) {
                //重连失败通知
            }
            @Override
            public void onReconnectSucceed(AlivcLivePusher pusher) {
                //重连成功通知
            }
            @Override
            public void onSendDataTimeout(AlivcLivePusher pusher) {
                //发送数据超时通知
            }
            @Override
            public void onConnectFail(AlivcLivePusher pusher) {
                //连接失败通知
            }

            @Override
            public String onPushURLAuthenticationOverdue(AlivcLivePusher alivcLivePusher) {
                return null;
            }

            @Override
            public void onSendMessage(AlivcLivePusher alivcLivePusher) {

            }
        });
        /**
         * 设置背景音乐播放通知事件
         * @param pushBGMListener 通知监听器
         */
        mAlivcLivePusher.setLivePushBGMListener(new AlivcLivePushBGMListener() {
            @Override
            public void onStarted() {
                //播放开始通知
            }
            @Override
            public void onStoped() {
                //播放停止通知
            }
            @Override
            public void onPaused() {
                //播放暂停通知
            }
            @Override
            public void onResumed() {
                //播放恢复通知
            }
            /**
             * 播放进度事件
             * @param progress 播放进度
             */
            @Override
            public void onProgress(final long progress, final long duration) {

            }

            @Override
            public void onCompleted () {
                //播放结束通知
            }
            @Override
            public void onDownloadTimeout () {
                //播放器超时事件，在这里处理播放器重连并且seek到播放位置
            }
            @Override
            public void onOpenFailed () {
                //流无效通知，在这里提示流不可访问
            }
        });
    }

    /**
     * 初始化配置
     */
    private void initSet() {
        AlivcLivePushConfig mAlivcLivePushConfig = new AlivcLivePushConfig();//初始化推流配置类
        mAlivcLivePushConfig.setResolution(AlivcResolutionEnum.RESOLUTION_540P);//分辨率540P，最大支持720P
        mAlivcLivePushConfig.setFps(AlivcFpsEnum.FPS_20); //建议用户使用20fps
        mAlivcLivePushConfig.setEnableBitrateControl(true); // 打开码率自适应，默认为true
        mAlivcLivePushConfig.setPreviewOrientation(AlivcPreviewOrientationEnum.ORIENTATION_PORTRAIT); // 默认为竖屏，可设置home键向左或向右横屏。
        mAlivcLivePushConfig.setAudioProfile(AlivcAudioAACProfileEnum.AAC_LC);//设置音频编码模式
        mAlivcLivePushConfig.setEnableBitrateControl(true);// 打开码率自适应，默认为true

        //流畅模式
        mAlivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_FLUENCY_FIRST );
        //自定义模式
//        mAlivcLivePushConfig.setQualityMode(AlivcQualityModeEnum.QM_CUSTOM);
//        mAlivcLivePushConfig.setTargetVideoBitrate(1200); //目标码率1200Kbps
//        mAlivcLivePushConfig.setMinVideoBitrate(400); //最小码率400Kbps
//        mAlivcLivePushConfig.setInitialVideoBitrate(900); //初始码率900Kbps

        mAlivcLivePushConfig.setEnableAutoResolution(true); // 打开分辨率自适应，默认为false

        setBackResult();

//        mAlivcLivePushConfig.setBeautyOn(true); // 开启美颜
//        mAlivcLivePushConfig.setBeautyLevel(AlivcBeautyLevelEnum.BEAUTY_Normal);//设定为基础美颜
//        mAlivcLivePushConfig.setBeautyWhite(70);// 美白范围0-100
//        mAlivcLivePushConfig.setBeautyBuffing(40);// 磨皮范围0-100
//        mAlivcLivePushConfig.setBeautyRuddy(40);// 红润设置范围0-100
//
//        mAlivcLivePushConfig.setBeautyOn(true); // 开启美颜
//        mAlivcLivePushConfig.setBeautyLevel(AlivcBeautyLevelEnum.BEAUTY_Professional);//设定为高级美颜
//        mAlivcLivePushConfig.setBeautyWhite(70);// 美白范围0-100
//        mAlivcLivePushConfig.setBeautyBuffing(40);// 磨皮范围0-100
//        mAlivcLivePushConfig.setBeautyRuddy(40);// 红润设置范围0-100
//        mAlivcLivePushConfig.setBeautyThinFace(40);// 瘦脸设置范围0-100
//        mAlivcLivePushConfig.setBeautyBigEye(30);// 大眼设置范围0-100
//        mAlivcLivePushConfig.setBeautyShortenFace(50);// 小脸设置范围0-100
//        mAlivcLivePushConfig.setBeautyCheekPink(15);// 腮红设置范围0-100

//        mAlivcLivePushConfig.setPausePushImage("退后台png图片路径");//设置用户后台推流的图片
//        mAlivcLivePushConfig.setNetworkPoorPushImage("网络差png图片路径");//设置网络较差时推流的图片置
//        mAlivcLivePushConfig.addWaterMark(waterPath, 0.1, 0.2, 0.3);//添加水印

//        mAlivcLivePushConfig.setPreviewRotation(AlivcPreviewRotationEnum rotation);//摄像头预览旋转角度
        //有些设备摄像头的连续对焦支持不好，sdk提供传感器感应移动实时对焦
        mAlivcLivePushConfig.setFocusBySensor(true);
        //预览显示模式配置
        mAlivcLivePushConfig.setPreviewDisplayMode(AlivcPreviewDisplayMode.ALIVC_LIVE_PUSHER_PREVIEW_ASPECT_FIT);
    }

    /**
     * 回调设置
     */
    private void setBackResult() {
        /**
         * 人脸识别回调（只接入标准版美颜可不需要调用此接口）
         **/
        mAlivcLivePusher.setCustomDetect(new AlivcLivePushCustomDetect()
        {
            @Override
            public void customDetectCreate() {
                taoFaceFilter = new TaoFaceFilter(getApplicationContext());
                taoFaceFilter.customDetectCreate();
            }
            @Override
            public long customDetectProcess(long data, int width, int height, int rotation, int format, long extra) {
                if(taoFaceFilter != null) {
                    return taoFaceFilter.customDetectProcess(data, width, height, rotation, format, extra);
                }
                return 0;
            }
            @Override
            public void customDetectDestroy() {
                if(taoFaceFilter != null) {
                    taoFaceFilter.customDetectDestroy();
                }
            }
        });
        /**
         * 美颜回调
         **/
        mAlivcLivePusher.setCustomFilter(new AlivcLivePushCustomFilter()
        {
            @Override
            public void customFilterCreate() {
                taoBeautyFilter = new TaoBeautyFilter();
                taoBeautyFilter.customFilterCreate();
            }
            @Override
            public void customFilterUpdateParam(float fSkinSmooth, float fWhiten, float fWholeFacePink, float fThinFaceHorizontal, float fCheekPink, float fShortenFaceVertical, float fBigEye) {
                if (taoBeautyFilter != null) {
                    taoBeautyFilter.customFilterUpdateParam(fSkinSmooth, fWhiten, fWholeFacePink, fThinFaceHorizontal, fCheekPink, fShortenFaceVertical, fBigEye);
                }
            }
            @Override
            public void customFilterSwitch(boolean on)
            {
                if(taoBeautyFilter != null) {
                    taoBeautyFilter.customFilterSwitch(on);
                }
            }
            @Override
            public int customFilterProcess(int inputTexture, int textureWidth, int textureHeight, long extra) {
                if (taoBeautyFilter != null) {
                    return taoBeautyFilter.customFilterProcess(inputTexture, textureWidth, textureHeight, extra);
                }
                return inputTexture;
            }
            @Override
            public void customFilterDestroy() {
                if (taoBeautyFilter != null) {
                    taoBeautyFilter.customFilterDestroy();
                }
                taoBeautyFilter = null;
            }
        });
    }

    public static void startActivity(Activity activity, AlivcLivePushConfig alivcLivePushConfig, String url, boolean async, boolean audioOnly, boolean videoOnly, AlivcPreviewOrientationEnum orientation, int cameraId, boolean isFlash, String authTime, String privacyKey, boolean mixExtern, boolean mixMain) {
        Intent intent = new Intent(activity, MyLivePushActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(AlivcLivePushConfig.CONFIG, alivcLivePushConfig);
        bundle.putString(URL_KEY, url);
        bundle.putBoolean(ASYNC_KEY, async);
        bundle.putBoolean(AUDIO_ONLY_KEY, audioOnly);
        bundle.putBoolean(VIDEO_ONLY_KEY, videoOnly);
        bundle.putInt(ORIENTATION_KEY, orientation.ordinal());
        bundle.putInt(CAMERA_ID, cameraId);
        bundle.putBoolean(FLASH_ON, isFlash);
        bundle.putString(AUTH_TIME, authTime);
        bundle.putString(PRIVACY_KEY, privacyKey);
        bundle.putBoolean(MIX_EXTERN, mixExtern);
        bundle.putBoolean(MIX_MAIN, mixMain);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, REQ_CODE_PUSH);
    }

    @Override
    protected void onDestroy() {
        if(mAlivcLivePusher != null) {
            try {
                mAlivcLivePusher.destroy();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
}
